package training.framework.presentation;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

import training.framework.business.AbstractEntityController;
import training.framework.business.AbstractEntitySearchOptions;
import training.framework.persistence.AbstractEntity;

@ManagedBean
@SessionScoped
public abstract class AbstractNewEntity <
Identifier, 
Entity extends AbstractEntity<Identifier>,
EntitySearchOptions extends AbstractEntitySearchOptions,
EntityPanel extends AbstractEntityPanel<Identifier, Entity>
>{
	private EntityPanel panel;
	private boolean entitySaved;
	private String savedMessage;
	private String initializeOutCome;
	private Class<EntityPanel> entityPanelClass;
	private Class<Entity> entityClass;	

	public AbstractNewEntity(
			Class<Entity> entityClass,
			Class<EntityPanel> entityPanelClass,
			String initializeOutCome, 
			String savedMessage) {

		if(entityClass == null){
			throw new IllegalArgumentException("entityClass == null");
		}
		if(entityPanelClass == null){
			throw new IllegalArgumentException("entityPanelClass == null");
		}
		if(initializeOutCome == null){
			throw new IllegalArgumentException("initializeOutCome == null");
		}
		if(savedMessage == null){
			throw new IllegalArgumentException("savedMessage == null");
		}
		this.entityClass = entityClass;
		this.entityPanelClass = entityPanelClass;
		this.initializeOutCome = initializeOutCome; 
		this.savedMessage = savedMessage;
	}

	public String initialize() throws InstantiationException, IllegalAccessException {
		Entity entity = entityClass.newInstance();
		this.panel = entityPanelClass.newInstance();
		this.panel.setEntity(entity);
		entitySaved = false;
		return this.initializeOutCome;
	}


	public EntityPanel getPanel() {
		return panel;
	}

	public boolean getEntitySaved() {
		return entitySaved;
	}	

	public void saveEntity() {
		FacesMessage message = new FacesMessage();

		AbstractEntityController<Identifier, Entity, EntitySearchOptions> controller = getController();
		controller.saveEntity(panel.getEntity());

		entitySaved = true;
		message.setSummary(savedMessage);
		message.setSeverity(FacesMessage.SEVERITY_INFO);
		FacesContext context = FacesContext.getCurrentInstance();
		context.addMessage(null, message);					
	}

	protected abstract AbstractEntityController<Identifier, Entity, EntitySearchOptions> getController();
}